package com.wzg.jetpack_blackbox.main;

import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.ViewModel;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.wzg.jetpack_blackbox.login.room.IUserDao;
import com.wzg.jetpack_blackbox.login.room.User;
import com.wzg.jetpack_blackbox.room.AppDataBase;

import java.util.List;

public class MainViewModel extends AndroidViewModel {

    public ObservableField<String> log = new ObservableField<>("Log: \n");

    IUserDao userDao;

    public MainViewModel(@NonNull Application application) {
        super(application);
        userDao = AppDataBase.getInstance().getUserDao();
    }


    public void onSearchClick(View v) {
        ThreadUtils.getCachedPool().execute(() -> {
            List<User> list = userDao.getAll();
            StringBuffer buffer = new StringBuffer("log:\t共：" + list.size() + "+\n\n");
            for (User item : list) {
                buffer.append("\n\n").append(GsonUtils.toJson(item));
            }
            log.set(buffer.toString());
            LogUtils.iTag("roomQueryByUserId", buffer.toString());
        });

    }

    public void update(View v) {
        ThreadUtils.getCachedPool().execute(() -> {
            try {
                User user = userDao.queryByUserId("007");
                user.setA("AAAA");
                user.setName("cba");
                userDao.update(user);
            } catch (Throwable e) {
            }


        });
    }

    public void add(View v) {
        ThreadUtils.getCachedPool().execute(() -> {
            User user = new User();
            user.setUserId("007");
            user.setName("abc");
            user.setLoginTime("2022-10-10");
            userDao.insertUser(user);

        });
    }

    public void delete(View v) {
        ThreadUtils.getCachedPool().execute(() -> {
            try {
                User a007 = userDao.queryByUserId("007");
                userDao.deleteUser(a007);
            } catch (Throwable e) {
            }
        });
    }


}
